package com.dabai.videobrowser.ui;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.dabai.dbutils.dialog.MdcDialog;
import com.dabai.dbutils.dialog.TipAlertDialog;
import com.dabai.dbutils.toast.DBToast;
import com.dabai.dbutils.utils.DabaiUtils;
import com.dabai.dbutils.utils.FileUtils;
import com.dabai.dbutils.utils.SharedPreferencesBasicUse;
import com.dabai.videobrowser.R;
import com.dabai.videobrowser.adapter.BatchTextAdapter;
import com.dabai.videobrowser.bean.BatchTextModel;
import com.dabai.videobrowser.utils.OtherUtils;
import com.google.android.material.switchmaterial.SwitchMaterial;
import com.google.android.material.textfield.TextInputLayout;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;

public class BatchRenameActivity extends AppCompatActivity {

    private TextInputLayout mTil1;

    private Button mButton1;
    private Context context;
    private Button mButton2;
    private SQLiteDatabase db;
    private RecyclerView mRecyclerview;
    private BatchTextAdapter batchTextAdapter;
    private Button mButton3;
    private TextView mTextview4;
    private SwitchMaterial mSwitch1;

    @Override
    protected void onDestroy() {
        TipAlertDialog.destroyTipLayout();
        db.close();
        super.onDestroy();
    }

    int ok = 0;
    int error = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_batch_rename);

        context = this;

        initViews();

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        SharedPreferencesBasicUse.init(context);


        db = openOrCreateDatabase("rules", Context.MODE_PRIVATE, null);
        String create = "create table if not exists rules(id integer primary key autoincrement,text1 text not null unique,text2 text not null);";
        db.execSQL(create);


        TipAlertDialog.init(context);

        mTil1.getEditText().setText(SharedPreferencesBasicUse.getString("lastPath2", ""));


        mButton1.setOnClickListener(v -> {

            OtherUtils.showInputDialog2(context, "添加规则", "", "", "被替换文字", "替换为", new OtherUtils.OnInputDialog2ButtonListener() {
                @Override
                public void confirm(AlertDialog dialog, String content1, String content2) {

                    if (content1.isEmpty()) {
                        return;
                    }

                    ContentValues in = new ContentValues();
                    in.put("text1", content1);
                    in.put("text2", content2);
                    db.insert("rules", null, in);

                    dialog.dismiss();
                    DBToast.showText(context, "已添加");

                    refreshList();
                }

                @Override
                public void cancel() {

                }
            }).getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

        });

        mButton2.setOnClickListener(v -> {

            File dir = new File(mTil1.getEditText().getText().toString());

            if (!dir.exists()) {
                DBToast.showYellowToast(context, "路径目标不存在!");
                return;
            }
            if (!dir.isDirectory()) {
                DBToast.showYellowToast(context, "路径目标必须是文件夹!");
                return;
            }

            if (batchTextAdapter.getData().size() <= 0 || dir.list().length <= 0) {
                DBToast.showYellowToast(context, "文件夹必须有文件,并且规则不能为空!");
                return;
            }

            MdcDialog.showConfirmDialog(context, "提示", dir.list().length + "个文件,是否开始重命名?", new MdcDialog.OnConfirmDialogButtonListener() {
                @Override
                public void confirm() {

                    SharedPreferencesBasicUse.setString("lastPath2", dir.getAbsolutePath());
                    TipAlertDialog.getInstance(context).showTipLayout("正在执行...");


                    ok = 0;
                    error = 0;

                    new Thread(() -> {

                        HashMap<String, String> hashMap = getAllRules();

                        for (File file1 : Objects.requireNonNull(dir.listFiles())) {


                            String socName = file1.getName();

                            String name = socName.substring(0,socName.lastIndexOf("."));
                            String suffix = socName.substring(socName.lastIndexOf("."));


                            File oldFile = new File(file1.getParentFile(), socName);


                            Log.d("DBTAG", "修改前 : "+name);

                            for (String key : hashMap.keySet()) {

                                try {
                                    name = name.replaceAll(key, hashMap.get(key));
                                } catch (Exception ignored) {

                                }

                            }

                            Log.d("DBTAG", "修改后 : "+name+"   后缀: "+suffix);

                            File newFile = new File(file1.getParentFile(), name+suffix);

                            if (oldFile.renameTo(newFile)) {
                                ok++;
                            } else {
                                error++;
                            }

                        }

                        runOnUiThread(() -> {
                            TipAlertDialog.getInstance(context).hideTipLayout();
                            DabaiUtils.showDialog(context, "成功" + ok + "个,"
                                    + "\n失败" + error + "个")
                                    .getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

                        });
                    }).start();

                }

                @Override
                public void cancel() {

                }
            }).getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

        });

        mButton3.setOnClickListener(v -> {

            MdcDialog.showInputDialog(context, "导入规则", "", "规则序列", new MdcDialog.OnInputDialogButtonListener() {
                @Override
                public void confirm(AlertDialog dialog, String content) {
                    if (content.isEmpty()) {
                        return;
                    }

                    String[] text1 = content.split(",");

                    for (String tmp : text1) {
                        ContentValues in = new ContentValues();
                        in.put("text1", tmp);
                        in.put("text2", "");
                        db.insert("rules", null, in);
                    }
                    dialog.dismiss();
                    DBToast.showText(context, "已添加" + text1.length + "个");
                    refreshList();
                }

                @Override
                public void cancel() {

                }
            }).getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

        });

        mButton3.setOnLongClickListener(v -> {

            MdcDialog.showConfirmDialog(context, "提示", "是否清空所有规则?", new MdcDialog.OnConfirmDialogButtonListener() {
                @Override
                public void confirm() {
                    String sql = "delete from rules";
                    String sql2 = "update sqlite_sequence SET seq =0 where name ='rules'";//自增长ID为0

                    db.execSQL(sql2);
                    db.execSQL(sql);

                    refreshList();

                }

                @Override
                public void cancel() {

                }
            }).getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

            return true;
        });

        refreshList();

    }


    public void refreshList() {

        mRecyclerview.setLayoutManager(new GridLayoutManager(context, 3));

        ArrayList<BatchTextModel> batchTextModels = new ArrayList<>();

        HashMap<String, String> hashMap = getAllRules();

        for (String key : hashMap.keySet()) {
            batchTextModels.add(new BatchTextModel(key, hashMap.get(key)));
        }

        batchTextAdapter = new BatchTextAdapter(batchTextModels);
        mRecyclerview.setAdapter(batchTextAdapter);

        mTextview4.setText("规则列表 (" + batchTextAdapter.getData().size() + ")");


        batchTextAdapter.setOnItemClickListener((adapter, view, position) -> {
            BatchTextModel batchTextModel = (BatchTextModel) adapter.getData().get(position);

            OtherUtils.showInputDialog2(context, "修改规则", batchTextModel.getText1(), batchTextModel.getText2()
                    , "被替换文字", "替换为", new OtherUtils.OnInputDialog2ButtonListener() {
                        @Override
                        public void confirm(AlertDialog dialog, String content1, String content2) {

                            if (content1.isEmpty()) {
                                return;
                            }

                            ContentValues in = new ContentValues();
                            in.put("text1", content1);
                            in.put("text2", content2);
                            db.update("rules", in, "text1 = ?", new String[]{batchTextModel.getText1()});

                            dialog.dismiss();
                            DBToast.showText(context, "已修改");

                            refreshList();
                        }

                        @Override
                        public void cancel() {

                        }
                    }).getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);
        });
        batchTextAdapter.setOnItemLongClickListener((adapter, view, position) -> {

            BatchTextModel batchTextModel = (BatchTextModel) adapter.getData().get(position);
            db.delete("rules", "text1 = ?", new String[]{batchTextModel.getText1()});
            refreshList();

            return true;
        });

    }


    /**
     * 把所有规则
     *
     * @return {@link HashMap<String, String>}
     */
    public HashMap<String, String> getAllRules() {
        HashMap<String, String> hashMap = new HashMap<>();

        String search = "select * from rules";
        Cursor cursor = db.rawQuery(search, null);


        while (cursor.moveToNext()) {

            hashMap.put(cursor.getString(cursor.getColumnIndex("text1"))
                    , cursor.getString(cursor.getColumnIndex("text2")));

        }
        cursor.close();
        return hashMap;
    }


    private void initViews() {
        mTil1 = findViewById(R.id.til1);
        mButton1 = findViewById(R.id.button1);
        mButton2 = findViewById(R.id.button2);
        mRecyclerview = findViewById(R.id.recyclerView);
        mButton3 = findViewById(R.id.button3);
        mTextview4 = findViewById(R.id.textView4);
        mSwitch1 = findViewById(R.id.switch1);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.home) {
            finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


}